package com.wangxiaonan.wxwork.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.wxwork.domain.Agent;
import com.wangxiaonan.wxwork.domain.Appchat;
import com.wangxiaonan.wxwork.domain.MessageTemplate;
import com.wangxiaonan.wxwork.domain.ScheduleJob;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: wangxiaonan
 * @Date: 2018/8/21
 **/
@Controller
//@RequestMapping("/")
public class WXController {
    private static final Logger logger = LoggerFactory.getLogger(WXController.class);
    @Resource
    private TokenService tokenService;
    @Resource
    private AgentService agentService;
    @Resource
    private AppChatService appChatService;
    @Resource
    private ScheduleService scheduleService;
    @Resource
    private MessageTemplateService messageTemplateService;

    /**
     * 首页
     *
     * @param limitStart
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping(value = {"/", "/index"})
    public String index(@RequestParam(value = "limit_start", required = false) Integer limitStart,
                        @RequestParam(value = "page_size", required = false) Integer pageSize, Model model) {

        List<Agent> agents = agentService.queryAgentList(limitStart, pageSize);
        JSONObject rs = new JSONObject();
        rs.put("status", "ok");
        if (agents == null) {
            rs.put("data", new JSONArray());
            return rs.toJSONString();
        }
        String token;
        JSONArray jsonArray = new JSONArray();
        for (Agent agent : agents) {
            JSONObject jsonAgent = new JSONObject();
            try {
                token = tokenService.getTokenString(agent.getCorpId(), agent.getSecret());
            } catch (ServiceException e) {
                logger.error("[WXController] index >>> {}", e.getMessage(), e);
                continue;
            }
            jsonAgent.putAll(agentService.getAgent(token, agent.getAgentId()));
            jsonArray.add(jsonAgent);
        }
        rs.put("data", jsonArray);

        model.addAttribute("agentList", jsonArray);
        return "/index";
    }

    /**
     * 应用消息
     *
     * @param agentId
     * @param model
     * @return
     */
    @RequestMapping(value = "/agent-message")
    public String message(@RequestParam(value = "agent_id") String agentId,
                          @RequestParam(value = "schedule_id", required = false) String scheduleId, Model model) {

        Agent agent = agentService.queryAgentById(agentId);
        if (agent == null) {
            model.addAttribute("status", "404");
            model.addAttribute("error_message", "404");
            return "/message";
        }
        if (StringUtils.isNotBlank(scheduleId)) {
            ScheduleJob scheduleJob = scheduleService.getScheduleJobById(Integer.valueOf(scheduleId));
            MessageTemplate messageTemplate = null;
            if (scheduleJob != null) {
                JSONObject data = JSONObject.parseObject(scheduleJob.getData());
                messageTemplate = messageTemplateService.getById(data.getInteger("template_id"));

            }
            if (messageTemplate != null) {
                JSONObject template = JSONObject.parseObject(messageTemplate.getTemplate());
                String type = template.getString("msgtype");
                model.addAttribute("msgtype", type);
                model.addAttribute(type + "_template_id", messageTemplate.getId());
                model.addAttribute(type + "_scheduleJob", scheduleJob);
                model.addAttribute(type + "_template", template);
            }
        }

        model.addAttribute("agent", agent);
        return "/message";
    }

    /**
     * 群聊列表
     *
     * @param agentId
     * @param model
     * @return
     */
    @RequestMapping(value = "/chats")
    public String chats(@RequestParam(value = "agent_id") String agentId, Model model) {

        Agent agent = agentService.queryAgentById(agentId);
        if (agent == null) {
            model.addAttribute("status", "404");
            model.addAttribute("error_message", "404");
            return "/chats";
        }

        List<Appchat> appChats = appChatService.queryByAgentId(agentId);
        String token;
        try {
            token = tokenService.getTokenString(agent.getCorpId(), agent.getSecret());
        } catch (ServiceException e) {
            model.addAttribute("status", e.getCode());
            model.addAttribute("error_message", e.getMsg());
            return "/chats";
        }

        JSONArray chatArray = new JSONArray();
        for (Appchat chat : appChats) {
            JSONObject chatJson = appChatService.getAppChat(token, chat.getChatId());
            if ("0".equals(chatJson.getString("errcode"))) {
                chatArray.add(chatJson.getJSONObject("chat_info"));
            } else {
                model.addAttribute("status", "404");
                model.addAttribute("error_message", "token invalid");
                return "/chats";
            }

        }

        model.addAttribute("agent", agent);
        model.addAttribute("chats", chatArray);
        return "/chats";
    }

    @RequestMapping(value = "/chats-create")
    public String createChat(@RequestParam(value = "agent_id") String agentId, Model model) {

        Agent agent = agentService.queryAgentById(agentId);
        if (agent == null) {
            model.addAttribute("status", "404");
            model.addAttribute("error_message", "404");
            return "/chats_create";
        }

        model.addAttribute("agent", agent);
        return "/chats_create";
    }

    @RequestMapping(value = "/chats-message")
    public String sendChatMessage(@RequestParam(value = "agent_id") String agentId,
                                  @RequestParam(value = "chat_id") String chatId, Model model) {

        Agent agent = agentService.queryAgentById(agentId);
        if (agent == null) {
            model.addAttribute("status", "404");
            model.addAttribute("error_message", "404");
            return "/chat_message";
        }

        Appchat appChat = appChatService.queryById(chatId);
        if (appChat == null) {
            model.addAttribute("status", "404");
            model.addAttribute("error_message", "chat not found");
            return "/chat_message";
        }
        String token;
        try {
            token = tokenService.getTokenString(agent.getCorpId(), agent.getSecret());
        } catch (ServiceException e) {
            model.addAttribute("status", e.getCode());
            model.addAttribute("error_message", e.getMsg());
            return "/chat_message";
        }

        JSONObject chatJson = appChatService.getAppChat(token, appChat.getChatId());
        if ("0".equals(chatJson.getString("errcode"))) {
            model.addAttribute("chat", chatJson.getJSONObject("chat_info"));
        } else {
            model.addAttribute("status", "404");
            model.addAttribute("error_message", "token invalid");
            return "/chat_message";
        }
        model.addAttribute("agent", agent);
        return "/chat_message";
    }

    @RequestMapping(value = "/timer-task")
    public String timerTask(@RequestParam(value = "agent_id") String agentId, Model model) {
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setGroup(agentId);
        List<ScheduleJob> scheduleJobs = scheduleService.getScheduleJobs(scheduleJob);

        Map<String, Boolean> currentStatus = new HashMap<>();
        for (ScheduleJob job : scheduleJobs) {
            currentStatus.put(job.getJobKey().toString(), scheduleService.checkExists(job.getJobKey()));
        }


        model.addAttribute("scheduleJobs", scheduleJobs);
        model.addAttribute("currentStatus", currentStatus);
        model.addAttribute("agentId", agentId);
        return "/schedule";
    }

}
